@file:JvmName("FragmentExtensions")

package com.example.mytestdemo.extensions

import android.os.Handler
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModelProvider

fun Fragment.doOnLifecycleEvent(doOnLifecycleEvent: () -> Unit, vararg targetEvents: Lifecycle.Event) {
    lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (targetEvents.contains(Lifecycle.Event.ON_ANY)) {
                doOnLifecycleEvent()
                return
            }
            if (targetEvents.contains(event)) {
                doOnLifecycleEvent()
            }
        }
    })
}

fun Fragment.doOnceOnLifecycleEvent(doOnceOnLifecycleEvent: () -> Unit, vararg targetEvents: Lifecycle.Event) {
    val viewModel = ViewModelProvider(this)[ActivityExtensionsViewModel::class.java]
    lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (targetEvents.contains(Lifecycle.Event.ON_ANY)) {
                if (!viewModel.terminated) {
                    doOnceOnLifecycleEvent()
                    viewModel.terminated = true
                }
                return
            }
            if (targetEvents.contains(event)) {
                if (!viewModel.terminated) {
                    doOnceOnLifecycleEvent()
                    viewModel.terminated = true
                }
            }
        }
    })
}

fun Fragment.safePostDelayed(delay: Long, run: () -> Unit) {
    safePostDelayed(delay, Lifecycle.Event.ON_DESTROY, run)
}

fun Fragment.safePostDelayed(delay: Long, stopOnEvent: Lifecycle.Event, runnable: () -> Unit) {
    val handler = Handler()
    val realRunnable = Runnable { runnable() }
    handler.postDelayed(realRunnable, delay)
    lifecycle.addObserver(object : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (stopOnEvent == event) {
                handler.removeCallbacks(realRunnable)
            }
        }
    })
}